<?php
/**
 * Add several features for lets member.
 *
 * @package    letsManager
 * @subpackage letsMember
 * @author     Jerome Fouilloy
 * @version    SVN: $Rev$
 */
class letsMemberActions extends sfActions
{
  public function executeUserAsksAndOffers(sfWebRequest $request)
  {
    $memberId = $request->getParameter('member_id',-1);
     
    // current user doesn't have right edit asks and offers for others we edit current user
    if($memberId == -1 || !$this->getUser()->hasCredential(LetsManagerRights::MANAGE_ASKS_OFFERS_OTHERS)
      || $memberId == $this->getUser()->getUserId())
    {
        $memberId = $this->getUser()->getUserId();
        $this->titleOffers = "Liste de mes offres";
        $this->titleAsks = "Liste de mes demandes";
        $this->getUser()->setCurrentReferer('@lets_user_asksAndOffers' ,'lets_actions');
    }
    else{
      $this->forward404Unless($member = MemberTable::getById($memberId));
      $memberName = $member->__toString();
      $this->titleAsks = "Liste des demandes de ".$memberName;
      $this->titleOffers = "Liste des offres de ".$memberName;
      // keep the current page link for cancel button of edit form
      $this->getUser()->setCurrentReferer('@lets_user_asksAndOffers?member_id='.$memberId ,'lets_actions');
    }
    $nbMaxAsksAndOffers = LetsConfiguration::nbMemberMaxiAsksAndOffers($this->getUser()->getAssociationId());
    // check number of asks and offers not override limit
    $this->canAddAskOrOffer = (LetsUserAskTable::countByMember($memberId)+LetsUserOfferTable::countByMember($memberId)) < $nbMaxAsksAndOffers;

    $this->userasks = LetsUserAskTable::getAllAsksForUser($memberId);
    $this->useroffers = LetsUserOfferTable::getAllOffersForUser($memberId);
    $this->nbMaxAsksAndOffers = $nbMaxAsksAndOffers;
    $this->member_id = $memberId;
    $this->getUser()->setCurrentReferer('@lets_user_asksAndOffers?member_id='.$memberId);
  }
  public function executeHomeManager(sfWebRequest $request)
  {
     
  }

  public function executeHomeMember(sfWebRequest $request)
  {
    $asso_id = $this->getUser()->getAssociationId();
    $this->current_user_id = $this->getUser()->getUserId();
    $this->asksExpire = LetsUserAskTable::getAsksExpirationNearest($asso_id,10);
    $this->offersNewest = LetsUserOfferTable::getOffersNewest($asso_id,10);
    $this->exchangesPending = LetsExchangeTable::getExchangesPendingForMember($this->current_user_id);
    $this->hasExchangesPending = count($this->exchangesPending) > 0;
    $this->member = LetsMemberTable::getById($this->current_user_id);
    $this->moneyMember = LetsMoneyAccountTable::getMoneyAvailable($this->current_user_id);
    $this->nextEvents = AssociationEventTable::getEventsNearest($asso_id,5);
    $this->newestMembers = LetsMemberTable::getNewestGuardUsers($asso_id,10);
    $this->getUser()->setCurrentReferer('@lets_home_member');
  }

  public function executeShow(sfWebRequest $request)
  {
    $user_id = $request->getParameter('id',-1);
    $this->member = MemberTable::getById($user_id);
    $this->forward404Unless($this->member);
    $this->userAsks = LetsUserAskTable::getAllAsksForUser($user_id);
    $this->userOffers = LetsUserOfferTable::getAllOffersForUser($user_id);
     
    if($this->getUser()->hasCredential(LetsManagerRights::SEE_DETAILS_MEMBER))
    {
      $this->setTemplate('showByManager');
    }
    else{
      $this->setTemplate('showByUser');
    }
  }

  public function executeAjaxSearch(sfWebRequest $request)
  {
    $cache = $this->getContext()->getViewCacheManager();
    
    $this->getResponse()->setContentType('application/json');
    $query   = $request->getParameter('q');
    $limit = $request->getParameter('limit',20);
    $canSeeAssociationMember = $this->getUser()->hasCredential(LetsManagerRights::USE_ASSOCIATION_MONEY);
    
  /*  $cacheQuery = 'letsMember/ajaxSearch?q='.url_encode($query).
      '&limit='.$limit.'&see_association='.($canSeeAssociationMember ? 1 : 0);
    if($cache != null && $cache->has($cacheQuery))
    {
      return $this->renderText($cache->get($cacheQuery));
    }*/
    $asso_id = $this->getUser()->getAssociationId();
    
    $members = LetsMemberTable::magicSearch($query, $limit, $asso_id,!$canSeeAssociationMember);
    $result  = array();

    foreach ($members as $member)
    {
      $key = $member->getId();
      $value = $member->getName().' ('.$member->getUsername().')';
      $result[$key] = $value;
    }

    if (count($result) === 0)
    {
      $result = null;
    }
    else
    {
      $result = json_encode($result);
    }
   /* if($cache != null)
    {
      $cache->set($result,$cacheQuery);
    }*/
    $ret = $this->renderText($result);
    return $ret;
  }
  /**
   * Search bar in offers / asks / members
   * @param sfWebRequest $request
   */
  public function executeSearchBar(sfWebRequest $request)
  {
    // $form = new LetsSearchBarForm();
    // $form->bind($request->getParameter($form->getName()));
    $type = $request->getParameter('type');
    
    $assoId = $this->getUser()->getAssociationId();
    //  if($form->isValid())
    {
      /*  $values = $form->getValues();
       $type = $values['type'];
       $query = $values['query'];*/
      if($type == LetsSearchBarForm::TYPE_MEMBER)
      {
        $this->executeListMembers($request);
        $this->setTemplate('listMembers');
      }
      else if($type == LetsSearchBarForm::TYPE_ASK)
      {
        $this->forward('letsUserAsk','index');
      }
      else if($type == LetsSearchBarForm::TYPE_OFFER)
      {
        $this->forward('letsUserOffer','index');
      }
    }
  }
  /**
   * Display all members 
   * @param sfWebRequest $request
   */
  public function executeListMembers(sfWebRequest $request)
  {

    $query = $request->getParameter('query','');

    $orderBy = $request->getParameter('orderby','username');
    $assoId = $this->getUser()->getAssociationId();
   
    $this->members = LetsMemberTable::magicSearch($query,-1,$assoId,true,$orderBy);
    // shortcut member usersame
    
    $this->queryForUrl = urlencode($query);
    // go on member detail
    if(count($this->members) === 1)
    {
      $this->redirect('@lets_user_show?id='.$this->members[0]->getId());
      return;
    }
    if($query == '' || $query == null)
    {
      $this->title = "Annuaire des adhérents";
    }
    else{
      $this->title = "Recherche '".$query."' dans les adhérents";
    }
  }
}

?>